package com.lottery.ruok.lottrey.utils;

import android.app.Activity;
import android.util.Log;

import com.lottery.ruok.lottrey.bean.IPStatus;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import property.SharePreferenceProperties;
import utils.Base64Utils;
import utils.LogUtil;
import utils.RSAUtils;
import utils.Utils;

/**
 * 作者：xuyf
 * <p>
 * 创建日期：2018/8/13$
 * <p>
 * 描述：
 */
public class LoadIPUtil {
    private final String TAG = "XYF_LoadIPUtil";
    private List<IPStatus> mIpStatus = new ArrayList<>();
    private boolean ipIsUse = false;
    private int pingCount = 0;
    private static Activity mActivity;
    private static LoadIPUtil instance = new LoadIPUtil();
    private ArrayList<String> arrURL;

    private LoadIPUtil() {
    }

    public static synchronized LoadIPUtil getInstance(Activity activity) {
        mActivity = activity;
        return instance;
    }

    public void downloadStandbyURL() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Common.GET_STANDBY_URL)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response != null && response.body() != null) {
                    String json = response.body().string();
                    if (json != null) {
                        ArrayList<String> arrRsa = Utils.getRsaUrlfromJson(json); // 從 Json 逐一分解出密文
                        if (arrRsa != null && arrRsa.size() > 0) {
                            arrURL = new ArrayList<>();
                            for (String rsa : arrRsa) {
                                try {
                                    InputStream inPrivate = new ByteArrayInputStream(Common.rsa_private_key.getBytes("UTF-8"));
                                    PrivateKey privateKey = RSAUtils.loadPrivateKey(inPrivate);
                                    byte[] data64 = Base64Utils.decode(rsa);
                                    byte[] decryptByte = RSAUtils.decryptData(data64, privateKey);
                                    if (decryptByte != null) {
                                        arrURL.add(new String(decryptByte));
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            for (int i = 0; i < arrURL.size(); i++) {
                                pingIP(arrURL.get(i));
                            }

                        }
                    }
                }
            }
        });
    }

    /**
     * @param ip 通过Rx发送agileIp的事件，取响应速度最快的
     */
    public void pingIP(final String ip) {
        Observable.create(new ObservableOnSubscribe() {
            @Override
            public void subscribe(ObservableEmitter e) {
                e.onNext(agileIp(ip));
            }
        }).timeout(10, TimeUnit.SECONDS, Observable.just(new IPStatus("", -1)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<IPStatus>() {

                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(IPStatus ipStatus) {
                        pingCount++;
                        if (ipStatus.getPingTime() != -1) {
                            mIpStatus.add(ipStatus);
                            UserInfo.saveIP(ipStatus.getIp());
                            ipIsUse = true;
                        }
                        if (pingCount == 1) {
                            UserInfo.replaceDomain();
                        }
                        postSlack();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void postSlack() {
        synchronized (LoadIPUtil.class) {
            if (pingCount == arrURL.size() - 1 && !ipIsUse && UserInfo.getNoNet() == 0) {
                new PostSlackUtils(mActivity, arrURL).doPost();
            }
        }
    }

    private IPStatus agileIp(String ip) {
        long startTime = System.currentTimeMillis();
        try {
            URL url = new URL(ip);
            String host = url.getHost();
            Process process = Runtime.getRuntime().exec("/system/bin/ping -c 1 -w 100 " + host);
            int status = process.waitFor();
            if (status == 0) {
                long pingTime = System.currentTimeMillis() - startTime;
                return new IPStatus(ip, pingTime);
            } else {
                return new IPStatus("", -1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new IPStatus("", -1);
    }
}
